<template>
  <el-card>
  <div class="user-list">
    
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" v-model="dialogVisible" style="width:500px;padding:50px;">
      <el-form :model="saveUserModel" ref="formRef" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userUsername">
          <el-input v-model="saveUserModel.userUsername" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword" label-width="80px">
          <el-input type="password" v-model="saveUserModel.userPassword" placeholder="建议初始密码为6个1"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="userNickname" label-width="80px">
          <el-input v-model="saveUserModel.userNickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <!-- 头像上传 -->
        <el-form-item label="头像" label-width="80px">
            <el-upload
                class="avatar-uploader"
                :action="'/api/upload/avatar'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
                <div style="position: relative; width: 100%; height: 100%">
                <el-avatar
                    v-if="saveUserModel.userAvatar"
                    :src="saveUserModel.userAvatar"
                    size="large"
                    style="width: 100px; height: 100px;"
                />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
                </div>
            </el-upload>
        </el-form-item>

        <!--选择是否是管理员-->
        <el-form-item label="是否是管理员">
             <el-radio-group v-model="saveUserModel.admin">
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="0" size="large">否</el-radio>
        </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </span>
      </template>
    </el-dialog>


  <!-- 搜索框 -->
    <div>
        <!-- 搜索框和按钮 -->
        <el-row justify="left" style="margin-top: 20px;">
          <el-col :span="16">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item>
                <el-input v-model="queryUser.userUsername" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
    </div>
   


    <!-- 用户列表 -->
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="userId" label="编号" width="80"></el-table-column>
      <el-table-column prop="userUsername" label="用户名称" width="100"></el-table-column>
      <el-table-column prop="userNickname" label="昵称" width="100"></el-table-column>
      <el-table-column prop="userPassword" label="密码"></el-table-column>
      <el-table-column prop="userAvatar" label="用户头像"></el-table-column>
      <el-table-column label="管理员" width="80">
        <template #default="scope">
            <el-tag v-if="scope.row.admin === 1" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
        </template>
    </el-table-column>
      <el-table-column fixed="right" label="操作" >
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editUser(scope.row)" v-if="userStore.hasPermission('user:update')">编辑</el-button>
          <el-button link type="danger" size="small" @click="deleteUser(scope.row.userId)">删除</el-button>
          <el-button link type="primary" size="small" @click="showRoleLog(scope.row.userId)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
      <!-- 分页 -->
    <el-pagination layout="prev, pager, next" :total="total" @current-change="handlePageChange"></el-pagination>
    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="showAddDialog">新增用户</el-button>
    </div>
  </div>


  <!-- 分配角色对话框  -->
  <el-dialog
    v-model="roleDialogVisible"
    title="分配角色"
    width="500"
    :before-close="handleClose"
  >
    <!-- 角色列表-->
    
    <el-checkbox-group v-model="checkedRoles">
      <template v-for="role in roleList" :key="role.roleId">
          <el-checkbox :label="role.roleName" :value="role.roleId" />
      </template>
    </el-checkbox-group>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="assinRole">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</el-card>
</template>

<script setup>


import { ref, onMounted ,reactive} from 'vue'
import { ElMessage } from 'element-plus'
// 导入接口
import { findPage ,insertUser,updateUserById,deleteById,getRoleIdsByUserId,grantRoles} from '../../api/sysUser'
import { getRoleList } from '../../api/sysRole'


import { useUserInfoStore } from '../../store/index' // 根据实际路径调整
const userStore = useUserInfoStore()

// 表格展示的数据
const users = ref([])
const total = ref(0)
// 分页查询参数
const queryUser = reactive({
  pageSize:10,
  currentPage:1,
  userUsername:''
})
// 角色对话框的数据
const roleDialogVisible = ref(false)
// 定义角色列表的数据
const roleList = ref([])
// 新增用户响应式数据
let saveUserModel = ref({
 userAvatar: '', // 存储头像URL
 userUsername:'',
 userPassword:'',
 userNickname:'',
 admin:0
})



const dialogVisible = ref(false)

const checkedRoles = ref([])

const currentUserId = ref()

// 展示出分配角色的对话框
const showRoleLog = async (id) => {
  roleDialogVisible.value = true
  let resp = await getRoleIdsByUserId(id)
  checkedRoles.value = resp.data
  currentUserId.value = id
}


// 分配角色
const assinRole = async () => {
  if(currentUserId.value){
    let resp = await grantRoles(currentUserId.value,checkedRoles.value)
    ElMessage.success(resp.message)
  }
  
   roleDialogVisible.value = false

}


// 条件查询
const  handleSearch = async() => {
  await fetchUsers()
}


// 上传成功回调
const handleAvatarSuccess = (response, file) => {
  // 假设后端返回的数据中包含 avatarUrl 字段
  newUser.value.userAvatar = response.avatarUrl || URL.createObjectURL(file.raw)
}

// 上传前校验（可选）
const beforeAvatarUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 2 // 限制大小为2MB

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }

  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  return true
}

const rules = {
  userUsername: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '长度必须在5-10个字符', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度必须在6-15个字符', trigger: 'blur' }
  ],
  userNickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  try{
    // 获取到数据
    const response = await findPage(queryUser)
    users.value = response.data.data
    total.value = response.data.total
  }catch(err){
    console.log(err)
  }
 
}

const fetchRoles = async()=>{
  // 获取角色列表
  let resp = await getRoleList()
  roleList.value = resp.data
}
// 组件挂载完成
onMounted(() => {
  // 从后端接口获取数据
  fetchUsers()
  fetchRoles()
  

})

// 处理分页
const handlePageChange = (currentPageValue) => {
  queryUser.currentPage = currentPageValue
  fetchUsers()
}

// 显示添加用户的对话框
const showAddDialog = () => {
  clearModel()
  dialogVisible.value = true
   
}

const clearModel = ()=>{
    // 清空数据
    saveUserModel.value = ref({
        userAvatar: '', // 存储头像URL
        userUsername:'',
        userPassword:'',
        userNickname:'',
        admin:0
        })
}

// 添加用户 | 修改
const addUser = async () => {
    if(saveUserModel.value.userId){
      // 调用接口
      try{
        console.log(saveUserModel.value)
        let resp =  await updateUserById(saveUserModel.value)

        ElMessage.success(resp.message)
        dialogVisible.value = false
      }catch(err){
        ElMessage.error("修改用户失败")
      }
    }else{
      try{
        let resp = await insertUser(saveUserModel.value)
        // 提示
        ElMessage.success(resp.message)
        // 隐藏对话框
        dialogVisible.value = false
        // 分页    
        await fetchUsers()
      } catch (error) {
       // console.error('添加用户失败:', error)
        ElMessage.error(添加用户失败)
      }
  }
}

// 编辑用户（这里只是一个简单的实现，实际应用中需要弹出表单）
const editUser = async (user) => {
  // 显示出对话框
  dialogVisible.value = true

  let obj = ref({})
  // copy数据
  Object.assign(obj.value,user)

  // 添加模型数据
  saveUserModel.value = obj.value

}

// 删除用户
const deleteUser = async (id) => {
  if(id){
     try {
      let response = await deleteById(id)
      ElMessage.success(response.message)
      await fetchUsers()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error("删除失败")
    }
  }
 
}

</script>


<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 10px;
  background-color: #fafafa;
  cursor: pointer;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>
